import { Directive, ElementRef, ViewContainerRef, TemplateRef, OnInit, Input } from '@angular/core';
import { NetProvider } from '../../providers/net/net';
import { GlobalsProvider } from '../../providers/globals/globals';
import { LoginPage } from '../../pages/login/login';

/**
 * Generated class for the EnumSelectDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
  selector: '[enum-select]' // Attribute selector
})
export class EnumSelectDirective implements OnInit {

  private enumname: string;

  constructor(private elementRef: ElementRef, private viewContainerRef: ViewContainerRef, private net: NetProvider, private globals: GlobalsProvider) {

  }

  @Input("enum-select")
  set value(val: string) {
    this.enumname = val;
  }

  ngOnInit() {
    let me = this;
    this.net.postJson(this.globals.urls.enums, { enumname: me.enumname }, (response) => {
      if (response && response.code) {
        if (response.code == "200") {
          me.fillSelect(me, me.elementRef.nativeElement, response);
        } else if (response.code == "401") {
          me.globals.navControl.setRoot(LoginPage);
        }
      }
    }, (error) => {

    });
  }

  fillSelect(me, node, response) {
    console.log(me, node, response);
    if (node && node.tagName && node.tagName.toUpperCase() == "SELECT") {
      for (let key in response.data) {
        let val = response.data[key];
        console.log(key, val);
        let option = document.createElement("option");
        option.setAttribute("value", key);
        let text = document.createTextNode(val);
        option.appendChild(text);
        node.appendChild(option);
      }
    } else if (node.childNodes) {
      node.childNodes.forEach((n) => {
        me.fillSelect(me, n, response);
      });
    }
  }

}
